package com.sws.worktive.job_service;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.widget.Toast;

import com.android.volley.NetworkError;
import com.android.volley.Response;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.sws.worktive.job_service.JobListJsonParser.JobData;

public class BaseFetcher {
	
	protected Context mContext;
	
	public static interface JobReceiverListener{
		void jobListReceived(JobData[] jobDatas);
	}
	
	protected Response.Listener<JSONObject> createSuccessListener(final JobReceiverListener jobReceiverListener){
		return new Response.Listener<JSONObject>() {
			@Override
			public void onResponse(JSONObject jsonObject) {
				try {
					if (!checkStatus(jsonObject)) {
						jobReceiverListener.jobListReceived(null);
						return;
					}
					JobData[] jobsDatas = new JobListJsonParser().parseJobsJsonObject(jsonObject);
					jobReceiverListener.jobListReceived(jobsDatas);
				} catch (JSONException e) {
					Toast.makeText(mContext, mContext.getString(com.sws.worktive.R.string.something_went_wrong), Toast.LENGTH_SHORT).show();
					jobReceiverListener.jobListReceived(null);
				}
				
			}
		};
	}
	
	protected Response.ErrorListener createErrorListener(final JobReceiverListener jobReceiverListener) {
		return new Response.ErrorListener() {
			@Override
			public void onErrorResponse(VolleyError error) {
				showErrorMessage(error);
				jobReceiverListener.jobListReceived(null);
			}
		};
	}
	
	protected boolean checkStatus(JSONObject jsonObject) throws JSONException{
		int status = jsonObject.getInt("status");
		if (status == 0) {
			String errorMessage = jsonObject.getString("message");
			if (errorMessage != null && errorMessage.length() >0) {
				Toast.makeText(mContext, errorMessage, Toast.LENGTH_SHORT).show();
			}else {
				Toast.makeText(mContext, mContext.getString(com.sws.worktive.R.string.server_down_message), Toast.LENGTH_SHORT).show();
			}
			return false;
		}
		return true;
	}
	
	protected void showErrorMessage(VolleyError error){
		String errorMessage = ""; 
		if (error instanceof TimeoutError) {
			errorMessage = mContext.getString(com.sws.worktive.R.string.time_out_message);
		}else if (error instanceof ServerError) {
			errorMessage = mContext.getString(com.sws.worktive.R.string.server_down_message);
		}else if (error instanceof NetworkError){
			errorMessage = mContext.getString(com.sws.worktive.R.string.internet_not_available);
		}else {
			errorMessage = mContext.getString(com.sws.worktive.R.string.something_went_wrong);
		}
		Toast.makeText(mContext, errorMessage, Toast.LENGTH_SHORT).show();
	}
	
}
